package org.kugua.library.impl;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.kugua.common.Constants;
import org.kugua.library.Library;
import org.kugua.library.Phrase;
import org.kugua.utils.RandomUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * PhraseLibrary
 *
 * @author 苦瓜
 * @create 2024/9/11 10:40
 * @since 1.0.0
 */
@Slf4j
public class PhraseLibrary implements Library<String> {

    /**
     * 词库文件名称
     */
    public static final String PHRASE_LIBRARY = "phrase.json";
    private final static List<String> LIBRARY = new ArrayList<>();

    static {
        try {
            ClassPathResource classPathResource =
                    new ClassPathResource(Constants.Path.LIBRARY_PATH + File.separator + PHRASE_LIBRARY);
            String contentAsString = classPathResource.getContentAsString(StandardCharsets.UTF_8);
            Phrase phrase = Optional.ofNullable(JSON.parseObject(contentAsString, Phrase.class))
                    .orElseGet(Phrase::new);
            LIBRARY.addAll(phrase.getPhrases());
            log.info("load phrase.json finished.phrase total: {}", phrase.getPhrases().size());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 随机获取1个内容
     *
     * @return T
     */
    @Override
    public String randomOne() {
        return LIBRARY.get(RandomUtils.random(LIBRARY.size()));
    }
}
